//
//  ViewController.m
//  AVPlayerLayer
//
//  Created by Xwoder on 17/2/3.
//  Copyright © 2017年 Xwoder. All rights reserved.
//

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>

#define KeyPath(obj, keyPath) @(((void)obj.keyPath, #keyPath))

@interface ViewController ()

@property (nonatomic, strong) AVPlayer *player;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"movie" withExtension:@"mp4"];
    AVAsset *asset = [AVAsset assetWithURL:url];
    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:asset];
    [playerItem addObserver:self
                 forKeyPath:KeyPath(playerItem, status)
                    options:NSKeyValueObservingOptionNew
                    context:NULL];
    AVPlayer *player = [[AVPlayer alloc] initWithPlayerItem:playerItem];
    
    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];
    playerLayer.frame = self.view.bounds;
    // videoGravity属性用来确定在承载层的范围内视频可以拉伸或缩放的程度
    playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    [self.view.layer addSublayer:playerLayer];
    
    self.player = player;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    // 当AVPlayerItem的status属性的值变为AVPlayerStatusReadyToPlay时，开始播放
    AVPlayerItem *playerItem = (AVPlayerItem *)object;
    if (playerItem.status == AVPlayerStatusReadyToPlay) {
        [self.player play];
    } else {
        
    }
}

// videoGravity可能的值
// AVLayerVideoGravityResize
// AVLayerVideoGravityResizeAspect
// AVLayerVideoGravityResizeAspectFill

@end
